/**
 * Copyright (c) 2018-present, Chen Guodong
 * All rights reserved.
 *
 * @flow
 */


<template>
  <div class="app">
    <div class="content">
      <!-- map -->
      <div id="map-content"></div>
      <div class="header">
        <div class="title">{{title}}</div>
        <div class="types">
          <div class="year" v-for="(item,index) in typeData" :key="index">
            <SelectType :data="item" :defaultData="pageTypes[item.key]"></SelectType>
          </div>
        </div>
        <MapLegend
          :legendData="legendData"
          :onePageVis="onePageVis"
          :unselectedStatus="unselectedStatus"
          :handlerMapLegend="handlerMapLegend"
        ></MapLegend>
      </div>
      <PageOne :onePageVis="onePageVis" :onePageData="onePageData"></PageOne>
      <pageTwo :onePageVis="onePageVis" :pageTypes="pageTypes" ref="pageTwo"></pageTwo>
      <div :class="['btns', onePageVis ? 'btnShow' : 'btnHide']">
        <el-button icon="el-icon-arrow-right" type="primary" circle class="btn" @click="changePage"></el-button>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { lazyAMapApiLoaderInstance } from "vue-amap";
import {
  reqMapInfo,
  reqProjectInfo,
  reqScreenInit,
  reqScreenInfo
} from "../../api/index.js";
import { showMessage } from "../../utils/index.js";
import config from "../../utils/config.js";
import PageOne from "./PageOne";
import SelectType from "./Select";
import Loading from "../../components/Loading";
// import PageTwo from "./PageTwo";
import MapLegend from "../../components/MapLegend";
import getAllData from "../../../mock/proj/proj_getAll.js";

const PageTwo = Vue.component("later", function(resolve) {
  setTimeout(function() {
    require(["./PageTwo"], resolve);
  }, 1000);
});

export default {
  data() {
    return {
      onePageData: {
        amount: {},
        area: {},
        user: {}
      }, //onePageData的数据集
      pageTypes: {},
      year: 0,
      area: [],
      parkId: 0,
      title: "", //标题
      onePageVis: true,
      allData: [], //所有项目的列表信息
      projectInfo: {},
      pointers: {}, //保存所有点位信息
      animatePointers: {}, //保存所有动画点位信息
      typeData: [], //分类数据
      legendData: [],
      unselectedStatus: [] //表示legend未选中的status, 空表示全部选中
    };
  },
  watch: {
    unselectedStatus: function(data) {
      let hideSeqno = [];
      let pointerVis = {};
      const self = this;
      const uns = this.unselectedStatus;
      const allData = this.allData;
      for (let i = 0; i < allData.length; i++) {
        if (uns.indexOf(allData[i].status) != -1) {
          pointerVis[allData[i].seqno] = false;
        } else {
          pointerVis[allData[i].seqno] = true;
        }
      }
      for (let j in pointerVis) {
        if (self.pointers[j]) {
          if (pointerVis[j]) {
            self.pointers[j].show();
          } else {
            self.pointers[j].hide();
          }
        }
        if (self.animatePointers[j]) {
          if (pointerVis[j]) {
            self.animatePointers[j].show();
          } else {
            self.animatePointers[j].hide();
          }
        }
      }
    },
    pageTypes: function(data) {
      this.$refs.pageTwo.reqAllData(data);
      this.reqScreenData();
    }
  },
  methods: {
    // 向后台获取数据
    async reqScreenData() {
      const self = this;
      const data = await reqScreenInit(self.pageTypes);
      if (data.code === 1) {
        self.allData = data.data.items;
        self.typeData = data.data.searchFields;
        self.title = data.data.title;
        self.legendData = data.data.legendData;
        self.onePageData = data.data.pandect;
        // 设置typeData初始值
        self.typeData.map(types => {
          if (
            types.values &&
            types.values.filter(k => k.selected === true)[0]
          ) {
            this.pageTypes[types.key] = types.values.filter(
              k => k.selected === true
            )[0].value;
          }
        });
        // pageTypes
        self.createMarks();
      } else {
        showMessage(self, "地图数据加载失败", "warning", "警告");
      }
    },
    // 初始化地图
    async initMap() {
      const self = this;
      self.mapObj = new AMap.Map("map-content", {
        mapStyle: "amap://styles/23a66b23dd15eaef820fe04440968168", //设置地图的显示样式
        viewMode: "3D",
        showBuildingBlock: true,
        expandZoomRange: true,
        pitch: 60,
        buildingAnimation: true,
        zoom: 13.5,
        zooms: [3, 18],
        center: [111.387972, 30.629671],
        layers: [
          new AMap.TileLayer({
            zIndex: 1,
            opacity: 1,
            // getTileUrl: "http://mt{1,2,3,0}.google.cn/vt/lyrs=y@142&hl=zh-CN&gl=cn&x=[x]&y=[y]&z=[z]&s=Galil&"
            getTileUrl:
              "http://t{1,2,3,4}.tianditu.gov.cn/DataServer?T=img_w&x=[x]&y=[y]&l=[z]"
          })
        ]
      });
      // 建立3D伍家岗区的区域边界

      //ajax获取全部点位相关信息
      await this.reqScreenData();

      // 将方法暴露到window中共模板拼接时调用
      window.clickLink = function(data, event) {
        var seqno = data.getAttribute("seqno");
        self.$router.push({
          path: "/screenProject",
          query: { seqno: seqno }
        });
      };
      window.closeMapWindow = () => {
        self.mapObj.clearInfoWindow();
      };
      // 监听地图zoom变化
      this.mapObj.on("zoomchange", () => {
        const zoom = this.mapObj.getZoom();
        if (zoom < config.middleZoom) {
          for (var item in self.pointers) {
            // 清空所有label
            self.pointers[item].setLabel({
              content: ""
            });
          }
        } else {
          for (var item in self.pointers) {
            // 清空所有label
            self.pointers[item].setLabel({
              //label默认蓝框白底左上角显示，样式className为：amap-marker-label
              offset: new AMap.Pixel(25, 5), //右侧
              zIndex: 99,
              content:
                "<div class='map-label'><span class='map-label-name'>" +
                self.allData.filter(b => b.seqno == item)[0].shortTitle +
                "</span><a href='javascript:void(0)' class='map-label-link' id='label-" +
                item +
                "' onclick='clickLink(this, event)' seqno='" +
                // "</span><a href='/Board/#/screenProject?seqno=WJQ2012-11' class='map-label-link' seqno='" +
                item +
                "'><i class='iconfont icon-arrow-double-right'></i></a></div>"
            });
            let btn = document.getElementById("label-" + item);
            if (btn) {
              btn.addEventListener(
                "touchstart",
                function(event) {
                  self.$router.push({
                    path: "/screenProject",
                    query: { seqno: item }
                  });
                },
                false
              );
            }
          }
        }
      });

      // 最后创建边界(用setTimeout临时解决Object3DLayer首次加载不成功的问题)
      setTimeout(function() {
        self.createAreaWall("伍家岗区");
      }, 1000);
    },
    // 在地图上创建区域边界
    createAreaWall(name) {
      const self = this;
      new AMap.DistrictSearch({
        subdistrict: 1, //返回下一级行政区
        extensions: "all", //返回行政区边界坐标组等具体信息
        level: "city" //查询行政级别为 市
      }).search(name, function(status, result) {
        var bounds = result.districtList[0].boundaries;
        self.redPolygon = new AMap.Polygon({
          path: bounds,
          borderWeight: 5, // 线条宽度，默认为 1
          strokeColor: "#ff0000", // 线条颜色
          fillOpacity: 0,
          map: self.mapObj
        });
      });
    },
    changePage() {
      this.onePageVis = !this.onePageVis;
    },
    // 创建marks
    createMarks() {
      const self = this;
      // 先清空所以点和动画点
      self.clearAllPointers();
      const allData = self.allData || [];
      allData.map((item, index) => {
        if (item.location.length < 2) {
          console.log("没有点位信息!");
        } else {
          // 创建一个 Marker 实例,并江点位信息保存在
          let marker = new AMap.Marker({
            position: item.location, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            offset: new AMap.Pixel(-10, -10),
            zIndex: 3,
            icon: require("../../assets/img/location/" + item.status + ".png") // 添加 Icon 图标 URL
          });
          // 如果项目正在实施中,则添加波动动画
          if (item.status && item.status === "IN_PROGRESS") {
            let markerContent =
              '<div class="ball-scale-multiple"><div></div><div></div><div></div></div>';
            let markerAnimate = new AMap.Marker({
              position: item.location, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              offset: new AMap.Pixel(-30, 20),
              zIndex: 2,
              content: markerContent,
              map: self.mapObj
            });
            self.animatePointers[item.seqno] = markerAnimate;
          }

          // 设置弹出框内容
          //构建自定义信息窗体
          function createInfoWindow(data) {
            var getStatusCN = function(data) {
              switch (data) {
                case "PLAN":
                  return "计划中";
                  break;
                case "IN_PROGRESS":
                  return "进行中";
                  break;
                case "COMPLETED":
                  return "已完成";
                  break;
                default:
                  return "未找到";
                  break;
              }
            };

            var info =
              '<div class="el-popover el-popper map-window" style="position: relative; width:' +
              window.chartFontSize * 34 +
              'px;">' +
              // 头部
              '<div class="header">' +
              '<div class="title">' +
              data.shortTitle +
              "</div>" +
              '<button type="button" class="btn" onclick="closeMapWindow()"><i class="iconfont icon-close"></i></button>' +
              "</div>" +
              // 主要内容区域
              '<div class="main">' +
              "<table>" +
              "<tbody>" +
              '<tr><td rowspan="3"><img src="' +
              data.litpic +
              '" alt="data.title"/></td><td class="label">项目编号</td><td class="value">' +
              data.seqno +
              "</td></tr>" +
              '<tr><td class="label">总面积</td><td class="value">' +
              data.levy_area +
              "㎡</td></tr>" +
              '<tr><td class="label">总户数</td><td class="value">' +
              data.levy_number +
              "户</td></tr>" +
              '<tr><td class="label">地址</td><td class="value" colspan="2">' +
              data.address +
              "</td></tr>" +
              '<tr><td class="label">状态</td><td class="value" colspan="2">' +
              getStatusCN(data.status) +
              "</td></tr>" +
              '<tr><td class="value" colspan="3">' +
              data.abstract +
              "</td></tr>" +
              "</tbody>" +
              "</table>" +
              '<div class="detailBtn"><a href="javascript:void(0)" onclick="clickLink(this)" seqno="' +
              data.seqno +
              '">查看详情>></a></div>' +
              "</div>" +
              // button
              // 箭头
              '<div x-arrow class="popper__arrow top-arrow" style="left: ' +
              ((window.chartFontSize * 34) / 2 - 5) +
              'px;"></div>' +
              "</div>";
            return info;
          }

          marker.on("click", async function(event) {
            self.mapObj.setFitView(this);
            const data = await reqScreenInfo({ seqno: item.seqno });
            if (data.code === 1) {
              self.infoWindow = new AMap.InfoWindow({
                isCustom: true, //使用自定义窗体
                content: createInfoWindow(data.data),
                offset: new AMap.Pixel(-6, -25)
              });
              self.infoWindow.open(self.mapObj, marker.getPosition());
            } else {
              showMessage(self, "项目信息获取失败!", "warning", "警告");
            }
          });
          self.mapObj.add(marker);
          self.pointers[item.seqno] = marker; //保存点位信息
        }
      });
    },
    // 清除地图所有的点
    clearAllPointers() {
      const self = this;
      // 先清除所有点位
      for (let i in self.pointers) {
        self.pointers[i].hide();
        self.mapObj.remove(self.pointers[i]);
      }
      for (let i in self.animatePointers) {
        self.animatePointers[i].hide();
        self.mapObj.remove(self.animatePointers[i]);
      }
      self.pointers = {};
      self.animatePointers = {};
    },
    // 切换legend选中状态
    handlerMapLegend(data) {
      const status = data.status;
      if (this.unselectedStatus.indexOf(status) != -1) {
        this.unselectedStatus.splice(this.unselectedStatus.indexOf(status), 1);
      } else {
        this.unselectedStatus.push(status);
      }
    }
  },
  mounted() {
    const self = this;
    lazyAMapApiLoaderInstance.load().then(() => {
      self.initMap();
    });
  },
  components: {
    PageOne,
    PageTwo,
    MapLegend,
    Loading,
    SelectType
  }
};
</script>

<style lang='less' scoped>
@import "../../utils/theme.less";

.app {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.content {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  // display: flex;
  // justify-content: center;
}
#map-content {
  width: 100%;
  height: 100%;
  // overflow: hidden;
  z-index: 1;
}
.header {
  position: absolute;
  top: 0;
  left: 0;
  height: 15%;
  width: 100%;
  z-index: 9999;
  color: #fff;
  // overflow: hidden;
  .el-dropdown-link {
    color: #fff !important;
    font-size: 1.2rem !important;
    font-weight: 600 !important;
  }
  .el-dropdown-menu__item {
    font-size: 1.2rem !important;
    font-weight: 600 !important;
  }
  .title {
    display: block;
    font-size: 3rem;
    font-weight: 600;
    padding: 2.2vw 0;
  }
  .types {
    display: inline-block;
    .year,
    .area {
      display: inline-block;
      font-size: 1.2rem;
      font-weight: 600;
      cursor: pointer;
    }
    .year {
      margin-right: 1vw;
    }
  }
}

.btns {
  transition: right ease-out 0.6s, transform ease-out 0.6s;
  position: fixed;
  top: 50% - 2vw;
  right: 2vw;
  z-index: 10;
  display: flex;
  justify-content: center;
  align-content: center;
  .btn {
    // height: 4vw;
    // width: 4vw;
    font-size: 2rem;
    display: flex;
    justify-content: center;
    align-content: center;
  }
}

.btnHide {
  right: 94vw;
  transform: rotate(180deg);
}

.btnShow {
  // right: auto;
  right: 2vw;
  transform: rotate(0deg);
}
</style>
